package Models;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import utils.GetConnection;

public class OrderLine{
	private Product product;
	private int qte;
	private long id;		
	
	public OrderLine(){}
	
	public OrderLine(long id) {
		PreparedStatement stm = null;
		try {
			String req = "select * from order_lines where id = ?;";
			stm = GetConnection.getConnection().prepareStatement(req);			
			stm.setLong(1, id);
			ResultSet res = stm.executeQuery();
			if(res.next()){
				this.id = res.getLong("id");
				this.product = new Product(res.getLong("product_id"));
				this.qte = res.getInt("qte");
			}
		}
		catch (SQLException e) {e.printStackTrace();}
		finally{
			try {
				if(stm != null) stm.close();
			} catch (SQLException e) {}
		}

	}
	
	
	public long getId() {return id;}
	public void setId(long id) {this.id = id;}
	public Product getProduct() {return product;}
	public void setProduct(Product product) {this.product = product;}
	public int getQte() {return qte;}
	public void setQte(int qte) {this.qte = qte;}
	
	public boolean create(long purchase_id){
		String req = "insert into order_lines(product_id,qte,purchase_id) values(?,?,?)";
		PreparedStatement stm = null;
		try {
			stm = GetConnection.preparedTransacStatement(req);
			
			stm.setInt(1, product.getId());
			stm.setInt(2, qte);
			stm.setLong(3, purchase_id);
			if(stm.executeUpdate() != 0)
				return true;
		} 
		catch (SQLException e) {e.printStackTrace();}
		finally{
			try { if( stm != null) stm.close(); } 
			catch (SQLException e) {}
		}
		
		return false;
	}

	public void removeItemFromStock() {
		product.removeProductFromStock(qte);
	}
}